package main

import (
	"log"
	"neecola.com/learngo/zhenai/util"
	"neecola.com/learngo/zhenai/models"
	"neecola.com/learngo/zhenai/config"
)

const (
	zhenghunUrl = "http://www.zhenai.com/zhenghun"
)

var (
	cityMoreChan = make(chan models.CityMoreInfo)
	cityChan     = make(chan models.CityInfo)
	userChan     = make(chan string)
)

// task scheduler use channel & select {}
func main() {

	const host   =":8888"

	// 分发第一个任务 ...
	go func(host string ) {

		client, err := util.GetJSONRpcClient(host)
		if err != nil {
			panic(err)
			return
		}

		var cityList []models.CityInfo
		err = client.Call(config.JSON_RPC_CITY_LIST, zhenghunUrl, &cityList)

		log.Printf("get city list  err %v\n", err)

		log.Printf("citylist = %+v \n",cityList)
		if err == nil {
			for _, v := range cityList {
				cityChan <- v

			}
		}
	}(host)


	// 简单粗暴的任务分发........
	for {

		log.Printf("-------")
		select {
		case cityInfo := <-cityChan:

			go func(url string) {

				var cityMore models.CityMoreInfo
				moreClient, err := util.GetJSONRpcClient(host)

				if err != nil {
					log.Printf("get json rpc error %s ", err)
					return
				}

				err = moreClient.Call(config.JSON_RPC_CITY_MORE, url, &cityMore)
				if err != nil {
					log.Printf("call %s but error %v\n", config.JSON_RPC_CITY_MORE, err)
					return
				}

				// 把更多城市的 用户连接和下一页的连接 塞进 去
				cityMoreChan <- cityMore

			}(cityInfo.Url)

		case more := <-cityMoreChan:

			log.Printf("more %v\n",more)
			for _, v := range more.UserUrl {

				go func(url string) {
					userChan <- v
				}(v)
			}

		case userUrl := <-userChan:
			go func(url string) {
				pro, err := util.GetJSONRpcClient(host)
				if err != nil {
					log.Printf("get user error %s \n", err)
					return
				}
				var profile models.Profile
				err = pro.Call(config.JSON_RPC_PROFILE, userUrl, &profile)
				if err != nil {
					log.Printf("call %s but get error %s \n", config.JSON_RPC_PROFILE, err)
					return
				}

				log.Printf("call %s get profile %v \n", config.JSON_RPC_PROFILE, profile)

			}(userUrl)

		}
	}

}
